
import dayjs from "dayjs"
import { useProjectStore } from "../store/projectStore"
import { useUserStore } from "../store/userStore"
import md5 from "js-md5"

const userStore=useUserStore()
const projectStore=useProjectStore()


const MyAlert=(params:{title:string,content:string})=>{

    return new Promise((resolve,reject)=>{
        uni.showModal({
        	title:params.title,
			content:params.content,
			success:(res)=>{
				if(res.confirm){
					resolve(true)
				}else{
					reject()
				}
			},
			fail: (res) => {
				reject(res)
			}
        })
    })

}

const defalutHeader=()=>{
	let header={}
	const token = userStore.getToken()
	if(token.length>0)
		header['x-token']=token
	const project = projectStore.getProject()
	if(project.id>0)
		header['x-project-id']=project.id
	header['Content-Type']='application/json'
	return header
}

const MyHttps={
	options:{
		url:"",
		data:{},
		method:"",
		header:{},
		responseType:"text",
		showError:true
	},
	setOptions(options){
		this.options={...this.options,...options}
		return this
	},
	post(url,data?):Promise<any>{
		this.setMethodData(url,'POST',data)
		return this.execute()
	},
	get(url,data?):Promise<any>{
		this.setMethodData(url,'GET',data)
		return this.execute()
	},
	setMethodData(url,method,data){
		this.options.method=method
		this.options.data=data
		this.options.url=url
	},
	uploadFile(url,fileUrl):Promise<any>{
		console.log(fileUrl)
		uni.showLoading({
			title:"加载中..."
		})
		this.options.header={...this.options.header,...defalutHeader()}
		return new Promise((resolve,reject)=>{
			uni.uploadFile({
				url: url,
				filePath: fileUrl,
				name: 'file',
				header: this.options.header,
				success: (res) => {
					let data=JSON.parse(res.data)
					if(data.code!=0){
						reject({source:res,msg:data.msg})
						if(data.code==3){
							userStore.logout()
						}
						return;
					}
					resolve(data)
					
				},
				complete:()=>{
					uni.hideLoading()
				},
				fail(err) {
					uni.showToast({
						title: '请求接口失败'
					})
					reject({source:err,msg:err.errMsg})
				}
			});
		}).catch((res)=>{
			if(this.options.showError){
				MyAlert({title:"操作失败",content:res.msg})
			}
			return Promise.reject(res)
		})
	},
	execute():Promise<any>{
		uni.showLoading({
			title:"加载中..."
		})
		this.options.header={...this.options.header,...defalutHeader()}
		return new Promise((resolve,reject)=>{
			const options=this.options
			uni.request({
				url:options.url,
				data:options.data,
				header:options.header,
				responseType:options.responseType,
				method:options.method,
				// timeout:10,
				success:(res)=>{
					// console.log(res.header)
					if(res.header['x-refresh-token']){
						userStore.setToken(res.header['x-refresh-token'])
					}
					if(res.statusCode==200 && (res.header['Content-Type']=="application/json" || res.header['content-type']=="application/json")){
						const data=res.data
						if(data.code!=0){
							reject({source:res,msg:data.msg})
							if(data.code==3){
								userStore.logout()
							}
							return
						}
						resolve(res.data)
					}
					
				},
				fail:(res)=>{
					console.log(res)
					reject({source:res,msg:res.errMsg})
				},
				complete() {
					uni.hideLoading()
				}
			})
		}).catch((res)=>{
			console.log(res)
			if(this.options.showError){
				MyAlert({title:"操作失败",content:res.msg})
			}
			// 返回一个 Promise.reject(res) 他就不往后then跑了
			return Promise.reject(res)
		})
	}
}

const FormatDate=(date:number|string|Date,format:string)=>{
	return dayjs(date).format(format)
}

const Md5Encode=(text)=>{
	return md5(text)
}

export {MyAlert,MyHttps,FormatDate,Md5Encode}